<template>
  <div class="fill-height">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">
          <el-icon class="title-icon"><DataAnalysis /></el-icon>
          环境监控
        </h1>
        <el-space>
          <el-button
            type="primary"
            @click="loadData"
            :loading="loading"
          >
            <el-icon><Refresh /></el-icon>
            刷新列表
          </el-button>
          <el-button
            type="warning"
            @click="cleanHistory"
            :loading="cleanLoading"
          >
            <el-icon><Delete /></el-icon>
            清理历史数据
          </el-button>
        </el-space>
      </div>
    </div>

    <!-- 搜索和过滤区域 -->
    <el-card class="search-card" header="搜索条件">
      <el-row :gutter="16">
        <el-col :span="6">
          <el-input
            v-model="searchForm.registerKey"
            placeholder="执行器标识"
            clearable
          />
        </el-col>
        <el-col :span="6">
          <el-input
            v-model="searchForm.appName"
            placeholder="应用名称"
            clearable
          />
        </el-col>
        <el-col :span="12">
          <el-space>
            <el-button
              type="primary"
              @click="loadData"
              :loading="loading"
            >
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-space>
        </el-col>
      </el-row>
    </el-card>

    <!-- 环境监控列表 -->
    <el-card class="table-card" header="最新环境监控快照">
      <el-table
        :data="monitorList"
        :loading="loading"
        style="width: 100%"
        row-key="id"
        size="default"
        @row-click="viewDetails"
      >
        <el-table-column prop="registerKey" label="执行器标识" width="200" show-overflow-tooltip />
        <el-table-column prop="appName" label="应用名称" width="150" />
        <el-table-column prop="osName" label="操作系统" width="150" show-overflow-tooltip/>
        <el-table-column prop="cpuUsagePercent" label="CPU使用率" width="120">
          <template #default="{ row }">
            <el-progress 
              :percentage="row.cpuUsagePercent" 
              :color="getUsageColor(row.cpuUsagePercent)"
              :stroke-width="8"
            />
          </template>
        </el-table-column>
        <el-table-column prop="systemMemoryUsagePercent" label="系统内存" width="120">
           <template #default="{ row }">
            <el-progress 
              :percentage="row.systemMemoryUsagePercent" 
              :color="getUsageColor(row.systemMemoryUsagePercent)"
              :stroke-width="8"
            />
          </template>
        </el-table-column>
        <el-table-column prop="heapMemoryUsagePercent" label="JVM堆内存" width="120">
           <template #default="{ row }">
            <el-progress 
              :percentage="row.heapMemoryUsagePercent" 
              :color="getUsageColor(row.heapMemoryUsagePercent)"
              :stroke-width="8"
            />
          </template>
        </el-table-column>
        <el-table-column prop="threadCount" label="线程数" width="100" />
        <el-table-column prop="monitorTime" label="监控时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.monitorTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click.stop="viewDetails(row)"
            >
              <el-icon><View /></el-icon>
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { DataAnalysis, Refresh, Delete, Search, View } from '@element-plus/icons-vue'
import { environmentMonitorApi } from '@/services/api'
import type { 
  EnvironmentMonitorQueryDTO, EnvironmentMonitorVO, 
  ApiResult, PageResult 
} from '@/types/job'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const cleanLoading = ref(false)
const monitorList = ref<EnvironmentMonitorVO[]>([])

// 搜索表单
const searchForm = reactive<EnvironmentMonitorQueryDTO>({
  registerKey: '',
  appName: '',
  pageNum: 1,
  pageSize: 10
})

// 分页信息
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 获取使用率颜色
const getUsageColor = (usage: number) => {
  if (usage < 60) return '#67C23A'
  if (usage < 80) return '#E6A23C'
  return '#F56C6C'
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString()
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const params: EnvironmentMonitorQueryDTO = {
      ...searchForm,
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize
    }

    const response: ApiResult<PageResult<EnvironmentMonitorVO>> = await environmentMonitorApi.queryEnvironmentMonitorPage(params)
    if (response.success) {
      monitorList.value = response.data.records
      pagination.total = response.data.total
    } else {
      ElMessage.error('加载环境监控数据失败: ' + response.message)
    }
  } catch (error) {
    console.error('加载环境监控数据出错:', error)
    ElMessage.error('加载环境监控数据出错')
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.registerKey = ''
  searchForm.appName = ''
  pagination.pageNum = 1
  loadData()
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.pageNum = 1
  loadData()
}

// 处理当前页变化
const handleCurrentChange = (page: number) => {
  pagination.pageNum = page
  loadData()
}

// 查看详情
const viewDetails = (row: EnvironmentMonitorVO) => {
  router.push(`/environment-monitor/${row.registerKey}`)
}

// 清理历史数据
const cleanHistory = async () => {
  try {
    const { value } = await ElMessageBox.prompt(
      '请输入要保留的天数（默认为30天），将清理该天数之前的历史数据。', 
      '确认清理', 
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^\d+$/,
        inputErrorMessage: '请输入有效的数字'
      }
    )

    cleanLoading.value = true
    const days = value ? parseInt(value, 10) : 30
    const response: ApiResult<string> = await environmentMonitorApi.cleanHistoryData(days)
    if (response.success) {
      ElMessage.success('清理历史数据任务已触发')
    } else {
      ElMessage.error('清理历史数据失败: ' + response.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清理历史数据出错:', error)
      ElMessage.error('清理历史数据出错')
    }
  } finally {
    cleanLoading.value = false
  }
}

// 页面加载时执行
onMounted(() => {
  loadData()
})
</script>

<style scoped>
/* 页面布局 */
.fill-height {
  min-height: 100vh;
  padding: 20px;
  background: #f5f7fa;
}

/* 页面标题 */
.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  display: flex;
  align-items: center;
  font-size: 24px;
  font-weight: 600;
  color: #1e293b;
  margin: 0;
}

.title-icon {
  margin-right: 12px;
  font-size: 28px;
  color: #f59e0b;
}

/* 搜索卡片 */
.search-card {
  margin-bottom: 20px;
  border: 2px solid #e2e8f0;
  border-radius: 0;
  box-shadow: 0 2px 8px rgba(30, 58, 138, 0.1);
}

/* 表格卡片 */
.table-card {
  border: 2px solid #e2e8f0;
  border-radius: 0;
  box-shadow: 0 2px 8px rgba(30, 58, 138, 0.1);
}

/* 现代化表格样式 */
.el-table {
  border: 2px solid #cbd5e1;
  border-radius: 0;
  box-shadow: 0 4px 12px rgba(30, 58, 138, 0.1);
  position: relative;
  overflow: hidden;
  cursor: pointer;
}

.el-table :deep(.el-table__header th) {
  background: #f1f5f9 !important;
  color: #475569;
  font-weight: 600;
  border-bottom: 2px solid #cbd5e1;
}

.el-table :deep(.el-table__body tr:hover) {
  background: #e3f2fd !important;
}

/* 分页容器 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 按钮样式 */
.el-button {
  border-radius: 0;
  font-weight: 600;
  border: 2px solid;
}
</style>
